package com.comfacauca.xmlc2.utils.tablas;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.annotation.Resource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
//import org.apache.log4j.Logger;

/**
 * The Database class performs all the necessary functions required to
 * SELECT, UPDATE, INSERT, and DELETE records from any database that 
 * supports SQL (Structured Query Language).
 * <h2>Setup:</h2>
 * This library of classes
 * are expected to be used in a JEE environment, and as such, it is 
 * assumed that you will be setting up an XML file for the Servlet
 * Container that describes the necessary parameters required to obtain
 * a database connection from a connection pool.  The XML file I am referring
 * to is generally named: <b>context.xml</b>.  This file should reside in a folder
 * named: <b>META-INF</b>.  The context.xml file would look similar to this:<br><br>
 * <blockquote>
 * <code>
 * &lt;!-- New Context for MySQL Database Driver --&gt;<br>
 * &lt;!-- The following URL will point you to the correct syntax regarding CONTEXTs:<br>
 *    http://jakarta.apache.org/tomcat/tomcat-5.5-doc/config/context.html --&gt;<br>
 * &lt;Context path="/JQuery" docBase="JQuery" debug="0"<br>
 * reloadable="true" crossContext="true"&gt;<br>
 *
 * &lt;!--Logger className="org.apache.catalina.logger.FileLogger"<br>
 *  prefix="localhost_jquery_log." suffix=".txt"<br>
 *  timestamp="true"/ --&gt;<br>
 * 
 *  &lt;Valve className="org.apache.catalina.valves.AccessLogValve"<br>
 *        prefix="localhost_jquery_log." suffix=".txt"<br>
 *        pattern="common"/&gt;<br>
 *
 *
 * &lt;Resource name="jdbc/fcs_db" auth="Container" type="javax.sql.DataSource" <br> 
 *  username="webapp" password="secret" driverClassName="com.mysql.jdbc.Driver"<br>
 *  url="jdbc:mysql://localhost:3306/fcs_db?autoReconnect=true"<br>
 *  maxActive="10" maxIdle="3" maxWait="10000"/&gt; <br>
 * 
 * &lt;/Context&gt;<br>
 * </code>
 * </blockquote>
 * This context.xml example is for reference only. It is being used to access a
 * MySQL database. This file was being used in a
 * Servlet Container named <a href="http://tomcat.apache.org/" target="main">Tomcat 7.0</a>. You will need to change the parameters
 * for your particular setup. Consult the documentation for your Servlet Container for
 * more information.  Your database drivers (contained in a jar file) for your particular system should reside
 * in the <b>WEB-INF\lib</b> folder. In our case, we were using the <i>mysql-connector-java-5.1.18.jar</i>.<br><br>
 * 
 * Your basic directory structure for your application should look like this:<br><br>
 * [home_dir]<br>
 * &nbsp;&nbsp;&nbsp;&nbsp;|<br>
 * &nbsp;&nbsp;&nbsp;&nbsp;index.html<br>
 * &nbsp;&nbsp;&nbsp;&nbsp;|_ media<br>
 * &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;|_ css<br>
 * &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;|_ js<br>
 * &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;|_ images<br> 
 * &nbsp;&nbsp;&nbsp;&nbsp;|_ META-INF<br>
 * &nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|_ context.xml<br>
 * &nbsp;&nbsp;&nbsp;&nbsp;|_WEB-INF<br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|_ classes<br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|_ lib<br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|_ jed-1.0.jar<br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|_ gson-2.2.4.jar<br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|_ log4j-1.2.8.jar<br>
 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|_ mysql-connector-java-5.1.18.jar<br><br>
 * <b>Usage Example:</b><br><br>
 * <code>
 * String dbName = "fcs_db";<br>
 * String[] tableNames = new String[]{"employees"};<br>
 * //Set the Primary Key field<br>
 * String pKey = "ID";<br>
 * Parameters params = new Parameters();<br>
 * //Acquire all the parameters passed to the Java Server Page<br>
 * ...<br>
 * Database db = new Database(dbName);<br>
 * Editor editor = new Editor(db, tableNames, pKey, params);<br>
 * </code>
 * @author Alan Shiers
 *
 */

public class Database
{
	public String name = "";
	public Query query = null;
	private Editor reference = null;
//	private Logger logger;
	private Context ctx = null;    
	private DataSource ds = null;
	public static enum RDBMS {MYSQL,ORACLE};	
	protected RDBMS dbtype = RDBMS.MYSQL;
	
	/**
	 * The default RDBMS type is MYSQL. If you want to specify some other RDBMS,
	 * use the other constructor.
	 * @param dbName
	 */
	public Database(String dbName)
	{
		try{
		name = dbName;
//		logger = Logger.getLogger(Database.class);
		ctx = new InitialContext();
		setDataSource(ctx);
		}
		catch(Exception e)
	    {
//	      if(Editor.isLoggingEnabled())
//	      {			
////	        logger.error("Database constructor: " + Editor.getFullStackTrace(e));
//		  }
//	      else
//	      {
//	    	  System.out.println(Editor.getFullStackTrace(e));
//	      }
	    }
	}
	/**
	 * Use this constructor if you want to specify an RDBMS other than MYSQL.
	 * @param dbName
	 * @param type
	 */
	public Database(String dbName, RDBMS type)
	{
		try{
		name = dbName;
		dbtype = type;
//		logger = Logger.getLogger(Database.class);
		ctx = new InitialContext();
		setDataSource(ctx);
		}
		catch(Exception e)
	    {
//	      if(Editor.isLoggingEnabled())
//	      {			
//	        logger.error("Database constructor: " + Editor.getFullStackTrace(e));
//		  }
//	      else
//	      {
//	    	  System.out.println(Editor.getFullStackTrace(e));
//	      }
	    }
	}
	
	@Resource
	private void setDataSource(Context context)
	{
		try{
			ds = (DataSource)ctx.lookup("java:comp/env/jdbc/" + name); 
		}
		catch(Exception e)
	    {
//	      if(Editor.isLoggingEnabled())
//	      {			
//	        logger.error("Database.createDataSource(): " + Editor.getFullStackTrace(e));
//		  }
//	      else
//	      {
//	    	  System.out.println(Editor.getFullStackTrace(e));
//	      }
	    }
	}
	
	/**
	 * Set a reference to an instance of the Editor class
	 * @param ref
	 */
	public void setEditorReference(Editor ref)
	{
		reference = ref;			
	}
	/**
	 * Set a reference to an instance of the Query class
	 * @param q
	 */
	public void setQuery(Query q)
	{
		query = q;
		query.setDatabase(this);
	}
	/**
	 * This form of the getConnection method is made available for convenience and does <b>NOT</b> attempt to derive a Connection from a connection pool.
	 * Instead, it obtains a Connection by accessing a JDBC Driver directly.<br><br>
	 * Example for connection to MySQL:<br><br>
	 * <pre>getConnection(Database.RDBMS.MYSQL,"org.gjt.mm.mysql.Driver","localhost","3306","scott", "tiger")</pre><br>
	 * Example for connection to Oracle:<br><br>
	 * <pre>getConnection(Database.RDBMS.ORACLE,"oracle.jdbc.OracleDriver","localhost","1521","scott","tiger")</pre><br><br>
	 * Don't forget to call closeConnection(Connection conn) when you are done with it. 
	 * @param type
	 * @param classForName
	 * @param URL
	 * @param PORT
	 * @param UserName
	 * @param Password
	 * @return Connection
	 */
	public Connection getConnection(RDBMS type,String classForName,String URL,String PORT,String UserName, String Password)
	{
		Connection connection = null;
		String connectionString = "jdbc:";
		
		try
	    {
	      if(type == RDBMS.MYSQL)
	      {	    	  
	    	  connectionString += "mysql://" + URL + ":" + PORT + "/" + name;
	      }
	      else if(type == RDBMS.ORACLE)
	      {
	    	  connectionString += "oracle:thin:@" + URL + ":" + PORT + ":" + name;
	      }
	      Class.forName(classForName).newInstance();
		  connection = DriverManager.getConnection(connectionString, UserName, Password);
	    }
		catch(SQLException sqle)
	    {
		  String extra = "SQL Problem: " + sqle.getMessage() + "\n";
		  extra += "SQL State: " + sqle.getSQLState() + "\n";
		  extra += "Vendor Error: " + sqle.getErrorCode() + "\n";	
//		  if(Editor.isLoggingEnabled())
//		  {			  	      
//		      logger.error(extra + Editor.getFullStackTrace(sqle));
//		  }
//		  else
//	      {
//	    	  System.out.println(extra + Editor.getFullStackTrace(sqle));
//	      }
	    }
	    catch(Exception e)
	    {
//	      if(Editor.isLoggingEnabled())
//	      {			
//	        logger.error("Database.getConnection(): " + Editor.getFullStackTrace(e));
//		  }
//	      else
//	      {
//	    	  System.out.println(Editor.getFullStackTrace(e));
//	      }
	    }
	    
	    return connection;
	}
	/**
	 * Obtain a Connection to perform a query. This method first
	 * creates a Context and performs a lookup on the system to obtain a DataSource object.
	 * From the DataSource, we return a Connection.  To use this method, it is assumed
	 * you have created a context.xml file in the META-INF directory. 
	 * <br><br>It is this method that is called directly by the methods:<br><br>
	 * executeSelect(), executeSelect(String strQuery, int columns),<br>
	 * executeInsertUpdate(),executeDeletes(Query[] queries)
	 * @return Connection
	 */
	public Connection getConnection()
	{
		Connection connection = null;
		try
	    {
	      if (ds != null)
	      {
	         connection = ds.getConnection();
	      }
	    }
		catch(SQLException sqle)
	    {
			String extra = "SQL Problem: " + sqle.getMessage() + "\n";
			extra += "SQL State: " + sqle.getSQLState() + "\n";
			extra += "Vendor Error: " + sqle.getErrorCode() + "\n";	
//			if(Editor.isLoggingEnabled())
//			{			  	      
//			    logger.error(extra + Editor.getFullStackTrace(sqle));
//			}
//			else
//		    {
//		    	System.out.println(extra + Editor.getFullStackTrace(sqle));
//		    }
	    }
	    catch(Exception e)
	    {
//	      if(Editor.isLoggingEnabled())
//	      {			
//	        logger.error("Database.getConnection(): " + Editor.getFullStackTrace(e));
//		  }
//	      else
//	      {
//	    	  System.out.println(Editor.getFullStackTrace(e));
//	      }
	    }
	    
	    return connection;
	}
	
	/**
	 * Close a Connection
	 * @param conn
	 */
	public void closeConnection(Connection conn)
	{
		try{
			conn.close();		
	    }
        catch(SQLException sqle)
        {
          String extra = "SQL Problem: " + sqle.getMessage() + "\n";
  		  extra += "SQL State: " + sqle.getSQLState() + "\n";
  		  extra += "Vendor Error: " + sqle.getErrorCode() + "\n";	
//  		  if(Editor.isLoggingEnabled())
//  		  {			  	      
//  		      logger.error(extra + Editor.getFullStackTrace(sqle));
//  		  }
//  		  else
//  	      {
//  	    	  System.out.println(extra + Editor.getFullStackTrace(sqle));
//  	      }
        }
        catch(Exception e)
        {
//          if(Editor.isLoggingEnabled())
//  	      {			
//  	        logger.error("Database.closeConnection(): " + Editor.getFullStackTrace(e));
//  		  }
//          else
//  	      {
//  	    	  System.out.println(Editor.getFullStackTrace(e));
//  	      }
        }
	}
	
	/**
	 * All data returned by this method will be obtained as a String
	 * regardless of each field type.
	 * @param query The query string
	 * @return a 2D String[][] array
	 */
	public String[][] executeSelect()throws IllegalArgumentException
	{
		if(query.getQueryType() != Query.Type.SELECT)
		{
			throw new IllegalArgumentException("You are trying to execute a query of type " + query.getQueryType().toString() + " using method executeSelect.");
		}
		
		Connection connection = null;
	    Statement statement = null;
	    ResultSet resultSet = null;
	    String[][] data = null;
	    
	    try{
	      connection = getConnection();
          if(connection != null)
          {
        	statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);        	
            resultSet = statement.executeQuery(query.toString());
            Field[] flds = query.getFields();
            int columns = flds.length;
            //move the cursor to the last record to obtain the record number
            resultSet.last();
            int recordCount = resultSet.getRow();
            //Dimension the String[][] array
            data = new String[recordCount][columns];
            //return the cursor to the first record
            resultSet.first();
            String temp = "";
            for(int i = 0; i < recordCount; i++)
            {
            	for(int j = 0; j < columns; j++)
                {
            		temp = resultSet.getString(j + 1);
            		if(temp == null || temp.equals("null"))
            		   data[i][j] = "";
            		else
            		   data[i][j] = temp;
                }
            	resultSet.next();
            }
            
            //If reference to the class Editor is null then this Database class isn't being used
            //in conjunction with the Editor class.  Therefore, we don't need to calculate the number
            //of records returned from the query.
            if(reference != null && reference.usingSSP)
            {
              //GET THE NUMBER OF RECORDS RETURNED BASED ON THE ORIGINAL QUERY.
              statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
              String queryStr = "";
              if(query.haveWhereConditions())
            	  queryStr = "SELECT COUNT(*) AS ROWS FROM " + query.getParentTable() + query.prepareWhere(query.getWhereConditions());
              else
            	  queryStr = "SELECT COUNT(*) AS ROWS FROM " + query.getParentTable();
     	   
              resultSet = statement.executeQuery(queryStr);
              resultSet.first();
              int foundrows = resultSet.getInt("ROWS");
              query.setIFilteredTotal(foundrows);
     	   
     	      //GET THE TOTAL NUMBER OF RECORDS IN THE TABLE.
     	      statement = connection.createStatement();
              queryStr = "SELECT COUNT(*) AS TOTAL FROM " + query.getParentTable();
     	      resultSet = statement.executeQuery(queryStr);
              resultSet.first();
              int ttl = resultSet.getInt("TOTAL");
              query.setITotal(ttl);
            }
                        
        	resultSet.close();
            resultSet = null;
            statement.close();
            statement = null;  
        	closeConnection(connection); 
        	connection = null;
          }
	    }
	    catch(SQLException sqle)
	    {
	    	String extra = "SQL Problem: " + sqle.getMessage() + "\n";
	  		extra += "SQL State: " + sqle.getSQLState() + "\n";
	  		extra += "Vendor Error: " + sqle.getErrorCode() + "\n";	
//	  		if(Editor.isLoggingEnabled())
//	  		{			  	      
//	  		    logger.error(extra + Editor.getFullStackTrace(sqle));
//	  		}
//	  		else
//	  	    {
//	  	       System.out.println(extra + Editor.getFullStackTrace(sqle));
//	  	    }
	    }
	    catch(Exception e)
	    {
	      if(Editor.isLoggingEnabled())
		  {
//	    	logger.error("Database.executeSelect - query: " + query.toString());	        
//	        logger.error(Editor.getFullStackTrace(e));
		  }
	      else
	  	  {
	    	 System.out.println("Database.executeSelect - query: " + query.toString());
	  	     System.out.println(Editor.getFullStackTrace(e));
	  	  }
	    }
	    finally
	    {
	      // Always make sure result sets and statements are closed,
	      // and the connection is returned to the pool
	      if (resultSet != null)
	      {
	        try { resultSet.close(); } catch (SQLException e) { ; }
	        resultSet = null;
	      }
	      if (statement != null)
	      {
	        try { statement.close(); } catch (SQLException e) { ; }
	        statement = null;
	      }	      
	      if (connection != null)
	      {
	        try { connection.close(); } catch (SQLException e) { ; }
	        connection = null;
	      }
	    }	    
	    
		return data;
	}
	/**
	 * This is a convenience method when a select query string is being supplied
	 * directly instead of using the Query object.
	 * @param strQuery
	 * @param columns
	 * @return A 2D String[][] array
	 */
	public String[][] executeSelect(String strQuery, int columns)
	{
		
		Connection connection = null;
	    Statement statement = null;
	    ResultSet resultSet = null;
	    String[][] data = null;
	    
	    try{
	      connection = getConnection();
          if(connection != null)
          {
        	statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);        	
            resultSet = statement.executeQuery(strQuery);
            
            //move the cursor to the last record to obtain the record number
            resultSet.last();
            int recordCount = resultSet.getRow();
            //Dimension the String[][] array
            data = new String[recordCount][columns];
            //return the cursor to the first record
            resultSet.first();
            String temp = "";
            for(int i = 0; i < recordCount; i++)
            {
            	for(int j = 0; j < columns; j++)
                {
            		temp = resultSet.getString(j + 1);
            		if(temp == null || temp.equals("null"))
            		   data[i][j] = "";
            		else
            		   data[i][j] = temp;
                }
            	if(i < recordCount - 1)
            	   resultSet.next();
            }
            
                                    
        	resultSet.close();
            resultSet = null;
            statement.close();
            statement = null;  
        	closeConnection(connection); 
        	connection = null;
          }
	    }
	    catch(SQLException sqle)
	    {
	    	String extra = "SQL Problem: " + sqle.getMessage() + "\n";
	  		extra += "SQL State: " + sqle.getSQLState() + "\n";
	  		extra += "Vendor Error: " + sqle.getErrorCode() + "\n";	
//	  		if(Editor.isLoggingEnabled())
//	  		{			  	      
//	  		    logger.error(extra + Editor.getFullStackTrace(sqle));
//	  		}
//	  		else
//	  	    {
//	  	       System.out.println(extra + Editor.getFullStackTrace(sqle));
//	  	    }
	    }
	    catch(Exception e)
	    {
	      if(Editor.isLoggingEnabled())
		  {
//	    	logger.error("Database.executeSelect - query: " + strQuery);
//	        logger.error(Editor.getFullStackTrace(e));
		  }
	      else
	  	  {
	    	 System.out.println("Database.executeSelect - query: " + strQuery); 
	  	     System.out.println(Editor.getFullStackTrace(e));
	  	  }
	    }
	    finally
	    {
	      // Always make sure result sets and statements are closed,
	      // and the connection is returned to the pool
	      if (resultSet != null)
	      {
	        try { resultSet.close(); } catch (SQLException e) { ; }
	        resultSet = null;
	      }
	      if (statement != null)
	      {
	        try { statement.close(); } catch (SQLException e) { ; }
	        statement = null;
	      }	      
	      if (connection != null)
	      {
	        try { connection.close(); } catch (SQLException e) { ; }
	        connection = null;
	      }
	    }	    
	    
		return data;
	}
	
	/*
	private boolean classExists(String clazz)
	{
		boolean exists = true;
		try{
			Class.forName(clazz);
		}
		catch(ClassNotFoundException fnfe)
		{
			exists = false;
		}
		return exists;
	}
	
	
	private boolean isJoinStatement(String query)
	{
		query = query.toLowerCase();
		boolean value = false;
		//First test for the keyword JOIN
		if(query.indexOf("join") > -1)
		{
		   value = true;
	       return value;	   
		}
		//Now, test for a comma separated list of table names after the FROM clause
		//Following are the keywords in the SQL language that follow the FROM clause
		String[] keywords = new String[]{"where","group by","having","order by","limit","procedure"};
		int fromIndex = query.indexOf("from");
		String sub1 = query.substring(fromIndex + 4, query.length()).trim();
		int nextIndex = -1;
		for(int i = 0; i < keywords.length; i++)
		{
		  nextIndex = sub1.indexOf(keywords[i]);
		  if(nextIndex > -1)
		  {
		    break; 
		  }
		}
		if(nextIndex == -1)
		{
		  //None of the keywords are in the query string
		  //Just check it for a comma.
		  if(sub1.indexOf(",") > -1)
		  {
		     value = true;
			 return value;
		  }
		  else
		  {
		    value = false;
			return value;
		  }
		}
		String sub2 = sub1.substring(0,nextIndex).trim();
		if(sub2.indexOf(",") > -1)
		{
		     value = true;		 
		}
		return value;
	}
	*/
	
	/**
	 * Execute an Insert or Update on a Query supplied to this class.
	 * @return A boolean informing success or not.
	 */
	public boolean executeInsertUpdate()throws IllegalArgumentException
	{
		if(query.getQueryType() != Query.Type.INSERT && query.getQueryType() != Query.Type.UPDATE)
		{
			throw new IllegalArgumentException("You are trying to execute a query of type " + query.type.toString() + " using method executeInsertUpdate.");
		}
		
		Connection connection = null;
	    PreparedStatement statement = null;
	    ResultSet resultSet = null;
	    boolean success = true;
	    	    
	    try{
	      connection = getConnection();
          if(connection != null)
          {
        	if(query.getQueryType() == Query.Type.INSERT)
            {  
        	  if(dbtype == RDBMS.MYSQL)
              {
        		if(query.isLinkTable() == false)  
        	      statement = connection.prepareStatement(query.toString(), PreparedStatement.RETURN_GENERATED_KEYS);
        		else
        		  statement = connection.prepareStatement(query.toString());	
              }
        	  else if(dbtype == RDBMS.ORACLE)
              {
        		  if(query.isLinkTable() == false)
        		     statement = connection.prepareStatement(query.toString(), query.getFieldsAsStringArray());
        		  else
        			 statement = connection.prepareStatement(query.toString(), query.getFieldsAsStringArrayWithoutID()); 
              }
            }
        	else
        	{
        	  statement = connection.prepareStatement(query.toString());
        	}
            statement.executeUpdate();
            if(query.getQueryType() == Query.Type.INSERT)
            {
            	//Get the id assigned to the new record
            	//If we are dealing with a Link Table then we don't need to retrieve any generated ids.
            	if(query.isLinkTable() == false)
            	{
            	  resultSet = statement.getGeneratedKeys();
                  if(resultSet != null && resultSet.next())
                  {
                    if(dbtype == RDBMS.MYSQL)
                    {
                      query.setNewRecordID(resultSet.getString(1));                    
                    }
                    else if(dbtype == RDBMS.ORACLE)
                    {
                	  query.setNewRecordID(resultSet.getString(1));
                    }
                    resultSet.close();
                    resultSet = null;
                 }
               }
            }
        	
            statement.close();
            statement = null;  
        	closeConnection(connection); 
        	connection = null; 
          }
	    }
	    catch(SQLException sqle)
	    {
	      success = false;
	      if(Editor.isLoggingEnabled())
		  {
	    	String extra = "Database.executeInsertUpdate - query: " + query.toString() + "\n";  
		    extra += "SQL Problem: " + sqle.getMessage() + "\n";
			extra += "SQL State: " + sqle.getSQLState() + "\n";
			extra += "Vendor Error: " + sqle.getErrorCode() + "\n";
//	    	if(sqle.getSQLState().indexOf("S1000") == -1)
//	    	{	    	  	      
//			  logger.error(extra + Editor.getFullStackTrace(sqle));
//	    	}
//	    	else
//	    	{
//	    	  System.out.println(extra + Editor.getFullStackTrace(sqle));
//	    	}
		  }
	    }
	    catch(Exception e)
	    {
	      success = false;
//	      if(Editor.isLoggingEnabled())
//		  {
//	    	logger.error("Database.executeInsertUpdate - query: " + query.toString());
//	    	logger.error(Editor.getFullStackTrace(e));
//		  }
//	      else
//	      {
//	    	System.out.println("Database.executeInsertUpdate - query: " + query.toString());
//	    	System.out.println(Editor.getFullStackTrace(e));
//	      }
	    }
	    finally
	    {
	      // Always make sure statements are closed,
	      // and the connection is returned to the pool
	      if (resultSet != null)
		  {
		     try { resultSet.close(); } catch (SQLException e) { ; }
		     resultSet = null;
		  }
	      if (statement != null)
	      {
	        try { statement.close(); } catch (SQLException e) { ; }
	        statement = null;
	      }
	      if (connection != null)
	      {
	        try { connection.close(); } catch (SQLException e) { ; }
	        connection = null;
	      }
	    }
	    return success;
	}	
	/**
	 * Execute a delete based on an array of Query objects.
	 * @param queries
	 */
	public void executeDeletes(Query[] queries)throws IllegalArgumentException
	{
		
		for(int i =0; i < queries.length; i++)
		{
			if(queries[i].getQueryType() != Query.Type.DELETE )
			{
				throw new IllegalArgumentException("You are trying to execute a query of type " + queries[i].getQueryType().toString() + " using method executeDeletes.");
			}
		}
		
		Connection connection = null;
	    PreparedStatement statement = null;
	    int i = 0;
	    	    	    
	    try{
	      connection = getConnection();
          if(connection != null)
          {
        	for(; i < queries.length; i++)
        	{          	  
        	  statement = connection.prepareStatement(queries[i].toString());
              statement.executeUpdate();
        	}
        	
            statement.close();
            statement = null;  
        	closeConnection(connection); 
        	connection = null; 
          }
	    }
	    catch(SQLException sqle)
	    {
	      String extra = "Database.executeDeletes - query: " + queries[i].toString() + "\n";  
		  extra += "SQL Problem: " + sqle.getMessage() + "\n";
		  extra += "SQL State: " + sqle.getSQLState() + "\n";
		  extra += "Vendor Error: " + sqle.getErrorCode() + "\n";	
//	      if(Editor.isLoggingEnabled())
//		  {	    	      
//			logger.error(extra + Editor.getFullStackTrace(sqle));
//		  }
//	      else
//	      {
//	    	  System.out.println(extra + Editor.getFullStackTrace(sqle));
//	      }
	    }
	    catch(Exception e)
	    {
//	    	if(Editor.isLoggingEnabled())
//			{
//		      logger.error("Database.executeDeletes: query: " + queries[i].toString());  
//		      logger.error(Editor.getFullStackTrace(e));
//			}
//	    	else
//		    {
//	    	  System.out.println("Database.executeDeletes: query: " + queries[i].toString());
//		      System.out.println(Editor.getFullStackTrace(e));
//		    }
	    }
	    finally
	    {
	      // Always make sure statements are closed,
	      // and the connection is returned to the pool
	      if (statement != null)
	      {
	        try { statement.close(); } catch (SQLException e) { ; }
	        statement = null;
	      }
	      if (connection != null)
	      {
	        try { connection.close(); } catch (SQLException e) { ; }
	        connection = null;
	      }
	    }	    
	}	
	
}


